package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.User;
import com.guomei.bean.curse.ByUserIdGetAllDTO;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.UserCourseLearn;
import com.guomei.bean.curse.vo.CourseLearnStat;
import com.guomei.bean.curse.vo.CourseLearnStatDto;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.mapper.curse.UserCourseLearnMapper;
import com.guomei.service.curse.UserCourseJoinService;
import com.guomei.service.curse.UserCourseLearnService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户课程学习记录Service实现类
 */
@Service
@Slf4j
@Transactional
public class UserCourseLearnServiceImpl implements UserCourseLearnService {
    @Resource
    private UserCourseLearnMapper userCourseLearnMapper;
    @Resource
    private CourseMapper courseMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private com.guomei.mapper.curse.CourseVideoMapper courseVideoMapper;
    @Resource
    private UserCourseJoinService userCourseJoinService;

    @Override
    public UserCourseLearn getById(Long id) {
        return userCourseLearnMapper.selectById(id);
    }

    @Override
    public UserCourseLearn getByUserAndVideo(Long userId, Long videoId) {
        return userCourseLearnMapper.selectByUserAndVideo(userId, videoId);
    }

    @Override
    public List<UserCourseLearn> listByUserAndCourse(Long userId, Long courseId) {
        return userCourseLearnMapper.selectByUserAndCourse(userId, courseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(UserCourseLearn userCourseLearn) {
        if (userCourseLearn == null || userCourseLearn.getUserId() == null || userCourseLearn.getVideoId() == null) {
            log.warn("保存学习记录参数不完整: userCourseLearn={}", userCourseLearn);
            return false;
        }
        
        // 先查询是否已存在相同用户和视频的学习记录
        UserCourseLearn existingRecord = userCourseLearnMapper.selectByUserAndVideo(
            userCourseLearn.getUserId(), 
            userCourseLearn.getVideoId()
        );
        
        LocalDateTime now = LocalDateTime.now();
        boolean success;
        Long courseId = null;
        Long userId = userCourseLearn.getUserId();
        
        if (existingRecord == null) {
            // 不存在记录，执行新增
            userCourseLearn.setCreatedTime(now);
            userCourseLearn.setUpdatedTime(now);
            // 设置默认值
            if (userCourseLearn.getLastLearnTime() == null) {
                userCourseLearn.setLastLearnTime(now);
            }
            if (userCourseLearn.getLearnDuration() == null) {
                userCourseLearn.setLearnDuration(0);
            }
            if (userCourseLearn.getProgress() == null) {
                userCourseLearn.setProgress(0);
            }
            if (userCourseLearn.getStatus() == null) {
                userCourseLearn.setStatus((short) 1); // 默认状态：学习中
            }
            log.info("新增学习记录: userId={}, videoId={}, courseId={}", 
                userCourseLearn.getUserId(), userCourseLearn.getVideoId(), userCourseLearn.getCourseId());
            success = userCourseLearnMapper.insert(userCourseLearn) > 0;
            courseId = userCourseLearn.getCourseId();
        } else {
            // 存在记录，执行更新
            existingRecord.setUpdatedTime(now);
            existingRecord.setLastLearnTime(now);
            
            // 更新传入的字段（如果不为空）
            if (userCourseLearn.getCourseId() != null) {
                existingRecord.setCourseId(userCourseLearn.getCourseId());
            }
            if (userCourseLearn.getLearnDuration() != null) {
                // 累计学习时长
                int currentDuration = existingRecord.getLearnDuration() != null ? existingRecord.getLearnDuration() : 0;
                existingRecord.setLearnDuration(currentDuration + userCourseLearn.getLearnDuration());
            }
            if (userCourseLearn.getProgress() != null) {
                if (userCourseLearn.getProgress() > existingRecord.getProgress()) {
                    existingRecord.setProgress(userCourseLearn.getProgress());
                }
                // existingRecord.setProgress(userCourseLearn.getProgress());
            }
            if (userCourseLearn.getStatus() != null) {
                existingRecord.setStatus(userCourseLearn.getStatus());
            }
            
            log.info("更新学习记录: userId={}, videoId={}, courseId={}, 累计时长={}", 
                existingRecord.getUserId(), existingRecord.getVideoId(), 
                existingRecord.getCourseId(), existingRecord.getLearnDuration());
            success = userCourseLearnMapper.update(existingRecord) > 0;
            courseId = existingRecord.getCourseId();
        }
        
        // 如果保存成功且有courseId，则更新课程整体学习进度
        if (success && courseId != null && userId != null) {
            try {
                userCourseJoinService.updateCourseProgress(userId, courseId);
                log.info("已同步更新课程学习进度: userId={}, courseId={}", userId, courseId);
            } catch (Exception e) {
                log.error("更新课程学习进度失败: userId={}, courseId={}", userId, courseId, e);
                // 注意：这里不影响视频学习记录的保存结果
            }
        }
        
        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProgress(Long userId, Long videoId, Integer progress, Integer duration) {
        // 查询是否已有记录
        UserCourseLearn learn = userCourseLearnMapper.selectByUserAndVideo(userId, videoId);
        LocalDateTime now = LocalDateTime.now();
        boolean success;
        Long courseId = null;

        if (learn == null) {
            // 新增记录
            learn = new UserCourseLearn();
            learn.setUserId(userId);
            learn.setVideoId(videoId);
            learn.setProgress(progress);
            learn.setLearnDuration(duration);
            learn.setStatus((short) 0); // 学习中
            learn.setLastLearnTime(now);
            learn.setCreatedTime(now);
            learn.setUpdatedTime(now);
            success = userCourseLearnMapper.insert(learn) > 0;
            courseId = learn.getCourseId();
        } else {
            // 更新记录
            learn.setProgress(progress);
            // 累计学习时长
            learn.setLearnDuration(learn.getLearnDuration() + duration);
            learn.setLastLearnTime(now);
            learn.setUpdatedTime(now);
            success = userCourseLearnMapper.update(learn) > 0;
            courseId = learn.getCourseId();
        }
        
        // 如果保存成功且有courseId，则更新课程整体学习进度
        if (success && courseId != null && userId != null) {
            try {
                userCourseJoinService.updateCourseProgress(userId, courseId);
                log.info("已同步更新课程学习进度: userId={}, courseId={}", userId, courseId);
            } catch (Exception e) {
                log.error("更新课程学习进度失败: userId={}, courseId={}", userId, courseId, e);
                // 注意：这里不影响视频学习记录的保存结果
            }
        }
        
        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        return userCourseLearnMapper.deleteById(id) > 0;
    }
    /**
     * 根据条件查询用户学习记录
     * @param userCourseLearn 查询条件
     * @return 用户学习记录列表
     */
    public Result<?> listByCondition(UserCourseLearn userCourseLearn) {
        PageHelper.startPage(userCourseLearn.getPageNum(), userCourseLearn.getPageSize());
        List<UserCourseLearn> userCourseLearns = userCourseLearnMapper.selectByCondition(userCourseLearn);
        
        // 联表查询 Course 信息
        if (userCourseLearns != null && !userCourseLearns.isEmpty()) {
            for (UserCourseLearn courseLearn : userCourseLearns) {
                if (courseLearn != null && courseLearn.getCourseId() != null) {
                    Course course = courseMapper.selectByIdWithTeacher(courseLearn.getCourseId());
                    if (course != null) {
                        courseLearn.setCourse(course);
                    } else {
                        log.info("{}课程不存在", courseLearn.getCourseId());
                    }
                }
            }
        }
        
        // 封装分页结果到PageData
        PageData<UserCourseLearn> pageData = new PageData<>();
        PageInfo<UserCourseLearn> pageInfo = new PageInfo<>(userCourseLearns);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(userCourseLearn.getPageNum());
        pageData.setPageSize(userCourseLearn.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> byUserIdGetAll(ByUserIdGetAllDTO byUserIdGetAllDTO) {
        if (byUserIdGetAllDTO == null || byUserIdGetAllDTO.getUserId() == null) {
            return Result.error("用户ID不能为空");
        }

        // 开启分页
        PageHelper.startPage(byUserIdGetAllDTO.getPageNum(), byUserIdGetAllDTO.getPageSize());

        UserCourseLearn userCourseLearn = new UserCourseLearn();
        userCourseLearn.setUserId(byUserIdGetAllDTO.getUserId());
        List<UserCourseLearn> userCourseLearns = userCourseLearnMapper.selectByCondition(userCourseLearn);

        if (userCourseLearns == null || userCourseLearns.isEmpty()) {
            return Result.fail("用户没有学习任何课程");
        } else {
            for (UserCourseLearn courseLearn : userCourseLearns) {
                if (courseLearn != null && courseLearn.getCourseId() != null) {
                    Course course = courseMapper.selectByIdWithTeacher(courseLearn.getCourseId());
                    if (course != null) {
                        courseLearn.setCourse(course);
                        if (course.getTeacherId() != null) {
                            User user = userMapper.selectById(course.getTeacherId());
                            if (user != null) {
                                courseLearn.setUser(user);
                            } else {
                                log.info("{}课程的教师不存在", courseLearn.getCourseId());
                            }
                        } else {
                            log.info("{}课程的教师不存在", courseLearn.getCourseId());
                        }
                    } else {
                        log.info("{}课程不存在", courseLearn.getCourseId());
                    }
                }
            }

            // 封装分页结果
            PageInfo<UserCourseLearn> pageInfo = new PageInfo<>(userCourseLearns);
            PageData<UserCourseLearn> pageData = new PageData<>();
            pageData.setTotal(pageInfo.getTotal());
            pageData.setData(pageInfo.getList());
            pageData.setPageNum(byUserIdGetAllDTO.getPageNum());
            pageData.setPageSize(byUserIdGetAllDTO.getPageSize());

            return Result.success(pageData);
        }
   }

    @Override
    public List<Long> getCourseIdsByUserId(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return userCourseLearnMapper.selectCourseIdsByUserId(userId);
    }

    @Override
    public Result<?> listByVideoIdsAndUserId(List<Long> videoIds, Long userId) {
        List<UserCourseLearn> userCourseLearns = userCourseLearnMapper.selectByVideoIdsAndUserId(videoIds, userId);
        if (userCourseLearns != null && !userCourseLearns.isEmpty()) {
            for (UserCourseLearn userCourseLearn : userCourseLearns) {
                if (userCourseLearn != null && userCourseLearn.getCourseId() != null) {
                    Course course = courseMapper.selectByIdWithTeacher(userCourseLearn.getCourseId());
                    if (course != null) {
                        userCourseLearn.setCourse(course);
                    }
                }
            }
        }
        return Result.success(userCourseLearns);
    }

    @Override
    public Result<?> getVideoLearnStats(CourseLearnStatDto dto) {
        if (dto == null || dto.getUserId() == null) {
            return Result.fail("用户ID不能为空");
        }

        // 开启分页
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        
        List<CourseLearnStat> courseLearnStats = userCourseLearnMapper.selectByVideoIds(dto);
        
        if (courseLearnStats == null || courseLearnStats.isEmpty()) {
            return Result.fail("用户没有学习任何课程");
        }

        // 封装分页结果
        PageInfo<CourseLearnStat> pageInfo = new PageInfo<>(courseLearnStats);
        PageData<CourseLearnStat> pageData = new PageData<>();
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(dto.getPageNum());
        pageData.setPageSize(dto.getPageSize());

        return Result.success(pageData);
    }

    @Override
    public boolean checkCourseProgress(Long userId, Long courseId) {
        if (userId == null || courseId == null) {
            log.warn("检查课程学习进度参数不完整: userId={}, courseId={}", userId, courseId);
            return false;
        }

        try {
            // 1. 获取该课程的所有视频
            List<com.guomei.bean.curse.CourseVideo> allVideos = courseVideoMapper.selectByCourseId(courseId);
            if (allVideos == null || allVideos.isEmpty()) {
                log.warn("课程{}没有视频", courseId);
                return false;
            }
            int totalVideos = allVideos.size();

            // 2. 获取用户对该课程的学习记录
            List<UserCourseLearn> learnRecords = userCourseLearnMapper.selectByUserAndCourse(userId, courseId);
            if (learnRecords == null || learnRecords.isEmpty()) {
                log.info("用户{}未学习课程{}", userId, courseId);
                return false;
            }

            // 3. 计算已完成的视频数量（status=1表示已完成）
            long completedVideos = learnRecords.stream()
                    .filter(record -> record.getStatus() != null && record.getStatus() == 1)
                    .count();

            // 4. 计算学习进度百分比
            double progress = (double) completedVideos / totalVideos * 100;
            log.info("用户{}课程{}学习进度: {}/{}={:.2f}%", userId, courseId, completedVideos, totalVideos, progress);

            // 5. 判断是否达到80%
            return progress >= 80.0;
        } catch (Exception e) {
            log.error("检查课程学习进度失败: userId={}, courseId={}", userId, courseId, e);
            return false;
        }
    }

    @Override
    public List<Long> getQualifiedCourseIds(Long userId) {
        if (userId == null) {
            log.warn("获取合格课程ID列表，用户ID为空");
            return new ArrayList<>();
        }

        try {
            // 1. 获取用户学习过的所有课程ID
            List<Long> allCourseIds = userCourseLearnMapper.selectCourseIdsByUserId(userId);
            if (allCourseIds == null || allCourseIds.isEmpty()) {
                log.info("用户{}没有学习任何课程", userId);
                return new ArrayList<>();
            }

            // 2. 过滤出学习进度达到80%的课程
            List<Long> qualifiedCourseIds = new ArrayList<>();
            for (Long courseId : allCourseIds) {
                if (checkCourseProgress(userId, courseId)) {
                    qualifiedCourseIds.add(courseId);
                }
            }

            log.info("用户{}共学习{}门课程，其中{}门达到80%进度", userId, allCourseIds.size(), qualifiedCourseIds.size());
            return qualifiedCourseIds;
        } catch (Exception e) {
            log.error("获取用户合格课程ID列表失败: userId={}", userId, e);
            return new ArrayList<>();
        }
    }
}
